﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MimeKit;
using Newtonsoft.Json;
using SkyWalkingDataDemo;
using SkyWalkingDataDemo.Model;

namespace SkyWalkingDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private IHttpClientFactory _httpClientFactory;
        private DbContext _dbContext;
        public WeatherForecastController(ILogger<WeatherForecastController> logger,
            IHttpClientFactory httpClientFactory, MyDbContext dbContext)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
            _dbContext = dbContext;
        }

        [HttpPost("AlarmMsg")]
        public async Task AlarmMsg(List<AlarmMsg> msgs)
        {
            string msg = "触发告警：";
            msg += msgs.FirstOrDefault()?.alarmMessage;
            _logger.LogDebug("msg");
            SendMail(msg);
           
        }
        private void SendMail(string content)
        {
            ///dynamic list = JsonConvert.DeserializeObject(content);
            //if (list != null && list.Count > 0)
            //{
                #region 构造消息内容
                StringBuilder sbMsg = new StringBuilder();
                sbMsg.AppendLine("服务发生异常,信息如下："+content);
                //foreach (var msgItem in list)
                //{
                //    sbMsg.AppendLine($"NodeInfo：{msgItem.Node}");
                //    sbMsg.AppendLine($"ServiceID：{msgItem.ServiceID}");
                //    sbMsg.AppendLine($"ServiceName：{msgItem.ServiceName}");
                //    sbMsg.AppendLine($"CheckName：{msgItem.Name}");
                //    sbMsg.AppendLine($"CheckStatus：{msgItem.Status}");
                //    sbMsg.AppendLine($"CheckOutput：{msgItem.Output}");
                //}
                #endregion
                #region 构造邮件发送信息
                var mailMsg = new MimeMessage();
                // 发送方
                mailMsg.From.Add(new MailboxAddress("ZoeSendMail", "发送邮箱@qq.com"));
                // 接收方
                mailMsg.To.Add(new MailboxAddress("ZoeReciveMail", "接收邮箱@qq.com"));
                //主题
                mailMsg.Subject = "SkyWalking报警";
                // 内容
                mailMsg.Body = new TextPart("plain")
                {
                    Text = sbMsg.ToString()
                };
                // 内容可以是html 
                ///var bodyBuilder = new BodyBuilder();
                //bodyBuilder.HtmlBody = @"<b>msgtext <i>italic</i></b>";
                //message.Body = bodyBuilder.ToMessageBody();
                #endregion
                using (var client = new SmtpClient())
                {
                    //允许所有SSL证书
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    //连接服务器
                    client.Connect("smtp.qq.com", 587, false);
                    //不需要OAuth2验证
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // SMTP 服务器需要认证,输入邮箱地址和获取到的授权码即可
                    client.Authenticate("1137xx3xxx7@qq.com 发送的邮箱", "授权码");
                    // 发送邮件
                    client.Send(mailMsg);
                    // 断开连接
                    client.Disconnect(true);

                }
            //}
        }

        [HttpGet("GetUser")]
        public async Task<IActionResult> GetUser()
        {
            var usr =  _dbContext.Set<User>().ToList();

            return Ok(usr);
        }

        [HttpGet]
        public async Task<IEnumerable<WeatherForecast>> Get()
        {
            //SendMail("sdfs");
            // 获取另一个API数据
            //HttpClient httpClient = _httpClientFactory.CreateClient();
            //var res =await httpClient.GetAsync("http://localhost:5100/weatherforecast");
            //string content = await res.Content.ReadAsStringAsync();

            int a = 0;
            int b = 1;
            int c = b / a;
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
